<!--
 * @Description: 
 * @Version: 1.0.0
 * @Author: gyh
 * @Date: 2021-07-24 10:37:07
 * @LastEditors: gyh
 * @LastEditTime: 2021-07-24 17:52:39
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      #ctx p:nth-child(odd) {
        background-color: #ccc;
        line-height: 36px;
        padding: 0 20px;
      }
      #ctx p:nth-child(even) {
        background-color: #ddd;
        line-height: 36px;
        padding: 0 20px;
      }
      .scroll {
        width: 50px;
        height: 50px;
        line-height: 25px;
        background-color: #f90;
        position: fixed;
        right: 20px;
        bottom: 20px;
        letter-spacing: 3px;
        text-align: center;
        font-size: 14px;
        color: #fff;
        display: none;
      }
    </style>
    <!-- <script src="./main.js"></script> -->
  </head>
  <body>
    <div id="ctx"></div>
    <div class="scroll" onclick="toTop(event)">返回顶部</div>
    <script>
      const ctx = document.getElementById('ctx')
      const scroll = document.getElementsByClassName('scroll')[0]
      const frag = document.createDocumentFragment()
      for (let index = 0; index < 300; index++) {
        const e = document.createElement('p')
        e.innerHTML = `第${index + 1}行`
        frag.appendChild(e)
      }
      ctx.appendChild(frag)
      let pageHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
      window.onscroll = function () {
        let top = document.body.scrollTop || document.documentElement.scrollTop
        if (top > pageHeight) {
          scroll.style.display = 'block'
        } else {
          scroll.style.display = 'none'
        }
      }
      let scrollToptimer
      function toTop() {
        scrollToptimer = setInterval(function () {
          let top = document.body.scrollTop || document.documentElement.scrollTop
          let speed = top / 4
          if (top > 0) {
            document.body.scrollTop = document.documentElement.scrollTop = top - speed
          } else {
            clearInterval(scrollToptimer)
          }
        }, 30)
      }
    </script>
  </body>
</html>
